package com.cloud.gateway.support;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;

/**
 * Web支持辅助
 *
 * @author fengwenjin
 * @since 2021/7/14
 */
public class WebSupport {
    /**
     * 允许跨域
     *
     * @param response
     */
    public static void allowCors(ServerHttpResponse response) {
        HttpHeaders headers = response.getHeaders();
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "*");
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        headers.set(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "18000");
    }

    /**
     * 获取请求来源IP
     *
     * @param request
     * @return String
     */
    public static String getRequestIP(ServerHttpRequest request) {
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.isEmpty(ip)) {
            ip = request.getHeaders().getFirst("X-Real-IP");
        }
        if (StringUtils.isEmpty(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
        } else {
            ip = ip.split(",")[0];
        }
        return ip.trim();
    }
}
